#!/usr/bin/env python
# coding: utf-8

"""
runtimer.py
create by cuiyu 2025-03-06
说明：
 * 说明内容

用法:
  runtimer.py

更新:
2025-03-06:
"""

import time
from loguru import logger as log
from contextlib import contextmanager

@contextmanager
def runtimer_create(timer_name: str="代码段"):
    class Result:
        elapsed = 0
        hours = 0
        minutes = 0
        seconds = 0
    result = Result()    
    start = time.time()
    yield result
    result.elapsed = time.time() - start
    # 时间分解逻辑
    result.hours = int(result.elapsed // 3600)
    result.minutes = int((result.elapsed % 3600) // 60)
    result.seconds = int(result.elapsed % 60)
    # 智能显示逻辑（自动隐藏0值）
    time_parts = []
    if result.hours > 0:
        time_parts.append(f"{result.hours}小时")
    if result.minutes > 0 or result.hours > 0:
        time_parts.append(f"{result.minutes}分")
    time_parts.append(f"{result.seconds}秒")
    log.info(timer_name + "耗时：" + "".join(time_parts))


def _main():
    # 使用示例
    with runtimer_create() as r:
        time.sleep(1)  # 模拟耗时操作（1小时1分40秒）
        # 这里放需要计时的代码

    # print(r)
    print(f"耗时：{r.elapsed:.2f}秒; {r.hours}小时{r.minutes}分{r.seconds}秒")


if __name__ == "__main__":
    # logging.basicConfig(level=logging.DEBUG) 
    _main()